<template>
  <div class="page-container">
    <!-- 筛选区卡片 -->
    <div class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item label="SN码">
          <el-input v-model="searchForm.sn" placeholder="请输入SN码" clearable />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.materialCode" placeholder="请输入物料编码" clearable />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="searchForm.batchNumber" placeholder="请输入批次号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="onAdd">新增</el-button>
      <el-button type="danger" :icon="Delete" @click="onDeleteSelected">批量删除</el-button>
      <el-button type="warning" :icon="Upload" @click="onExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        height="100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编码" width="120" />
        <el-table-column prop="materialName" label="物料名称" width="120" />
        <el-table-column prop="specification" label="规格型号" width="120" />
        <el-table-column prop="flats" label="单位" width="60" />
        <el-table-column prop="batchNumber" label="批次号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="quantity" label="数量" width="80" align="right" />
        <el-table-column prop="productionTime" label="生成时间" width="160" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 新增SN码弹窗 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="生成SN码" 
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form 
          ref="formRef" 
          :model="formData" 
          :rules="formRules" 
          label-width="100px"
          class="dialog-form"
        >
          <el-form-item label="物料编码" prop="materialCode" required>
            <div class="input-with-icon">
              <el-input
                v-model="formData.materialCode"
                placeholder="请点击选择物料编码"
                readonly
                @click="openMaterialSelector"
              />
              <el-button :icon="Search" class="search-btn" circle @click="openMaterialSelector"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="formData.materialName" disabled />
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input v-model="formData.specification" type="textarea" :rows="3" disabled />
          </el-form-item>
          <el-form-item label="批次号" prop="batchNumber">
            <el-input v-model="formData.batchNumber" placeholder="请输入批次号" />
          </el-form-item>
          <el-form-item label="SN码数量" prop="quantity" required>
            <div class="quantity-input">
              <el-button @click="decreaseQuantity">-</el-button>
              <el-input-number 
                v-model="formData.quantity" 
                :min="1" 
                :max="1000" 
                controls-position="right" 
                style="width: 100%"
              />
              <el-button @click="increaseQuantity">+</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料选择对话框 -->
    <el-dialog
      v-model="materialSelectorVisible"
      title="物料产品选择"
      width="80%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="material-selector-dialog"
    >
      <div class="material-selector-container">
        <!-- 目录树和表格布局 -->
        <div class="selector-body">
          <!-- 左侧分类目录树 -->
          <div class="category-tree">
            <div class="tree-header">
              <span class="tree-title">物料分类</span>
              <el-button text :icon="RefreshRight" @click="loadCategoryTree"></el-button>
            </div>
            <el-tree
              ref="categoryTreeRef"
              :data="categoryTree"
              :props="{ 
                label: 'classifyName',
                children: 'children'
              }"
              node-key="orderId"
              highlight-current
              default-expand-all
              @node-click="handleCategorySelect"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span v-if="!data.children || !data.children.length">
                    <el-icon><Document /></el-icon>
                  </span>
                  <span v-else>
                    <el-icon><Folder /></el-icon>
                  </span>
                  <span>{{ node.label }}</span>
                </div>
              </template>
            </el-tree>
          </div>
          
          <!-- 右侧物料表格 -->
          <div class="material-table">
            <el-table
              ref="materialTableRef"
              :data="materialList"
              border
              highlight-current-row
              height="450px"
              v-loading="materialLoading"
              @row-click="handleMaterialRowClick"
            >
              <el-table-column width="50">
                <template #default="{ row }">
                  <el-radio v-model="selectedMaterialId" :label="row.id || row.orderId" @change="() => handleRadioChange(row)">&nbsp;</el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="materialCode" label="物料编码" min-width="120" />
              <el-table-column prop="materialName" label="物料名称" min-width="180" />
              <el-table-column prop="specification" label="规格型号" min-width="120" />
              <el-table-column prop="unit" label="单位" width="80" />
              <el-table-column prop="materialType" label="物料/产品" width="100">
                <template #default="{ row }">
                  <el-tag type="info">{{ row.materialType === 1 ? '物料' : '产品' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column fixed="right" label="操作" width="80">
                <template #default="{ row }">
                  <el-button link type="primary" @click.stop="selectMaterial(row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialSelectorVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!selectedMaterial">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/api/http';
import { Search, Plus, Delete, Upload, RefreshRight, Document, Folder } from '@element-plus/icons-vue';

// API基础路径
const baseApiUrl = '/api/SNTables/GetSNTable';

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  sn: '',
  materialCode: '',
  materialName: '',
  batchNumber: ''
});

// 表格数据
const tableData = ref([]);

// 分页相关
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
});

// 选中的行
const selectedRows = ref([]);

// 新增弹窗相关
const addDialogVisible = ref(false);
const formRef = ref();
const formData = reactive({
  materialId: '',
  materialCode: '',
  materialName: '',
  specification: '',
  batchNumber: '',
  quantity: 1,
});

// 表单验证规则
const formRules = {
  materialCode: [
    { required: true, message: '请选择物料编码', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入SN码数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
};

// 物料选项
const materialOptions = ref([]);

// 物料选择相关
const materialSelectorVisible = ref(false);
const categoryTree = ref([]);
const materialList = ref([]);
const selectedMaterialId = ref(null);
const materialLoading = ref(false);
const selectedMaterial = ref(null);

// 记录选中的分类ID
const selectedCategoryId = ref(null);

// 生命周期钩子
onMounted(() => {
  // 初始化加载数据
  getTableData();
});

// 加载表格数据
const getTableData = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      quantity: searchForm.quantity || 0,
      materialCode: searchForm.materialCode || null,
      materialName: searchForm.materialName || null,
      batchNumber: searchForm.batchNumber || null
    };

    // API调用 - 获取SN码列表
    const response = await http.post(`/api/SNTables/GetSNTable`, params);
    console.log('API响应数据:', response);

    if (response && response.status) {
      tableData.value = response.rows || [];
      pagination.total = response.total || 0;
    } else {
      ElMessage.error(response?.message || '获取数据失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = () => {
  pagination.pageIndex = 1;
  getTableData();
};

// 重置搜索
const onReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  pagination.pageIndex = 1;
  getTableData();
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
  console.log('选中行数组:', selectedRows.value);
};

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.pageIndex = val;
  getTableData();
};

// 新增
const onAdd = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 设置默认值
  formData.materialId = '';
  formData.materialName = '';
  formData.specification = '';
  formData.batchNumber = '';
  formData.quantity = 1;
  formData.prefix = '';
  
  addDialogVisible.value = true;
};

// 物料选择相关功能
const searchMaterials = async () => {
  try {
    materialLoading.value = true;
    
    // 构建查询参数
    const params = {
      categoryId: selectedCategoryId.value || null
    };
    
    // API调用 - 获取物料列表
    const response = await http.get('/api/MaterialCatalogs/GetTree', params);
    
    if (response && response.status) {
      materialList.value = response.rows || [];
    } else {
      ElMessage.error(response?.message || '获取物料列表失败');
      materialList.value = [];
    }
  } catch (error) {
    console.error('获取物料列表出错:', error);
    ElMessage.error('获取物料列表失败，请稍后再试');
    materialList.value = [];
  } finally {
    materialLoading.value = false;
  }
};

const loadCategoryTree = async () => {
  try {
    // API调用 - 获取物料分类树
    const response = await http.get('/api/MaterialCatalogs/GetTree');
    
    if (response) {
      // 转换数据结构
      categoryTree.value = Array.isArray(response) ? response : [response];
      console.log('分类树数据:', categoryTree.value);
    } else {
      ElMessage.warning('获取物料分类树失败');
      categoryTree.value = [];
    }
  } catch (error) {
    console.error('获取物料分类树出错:', error);
    ElMessage.error('获取物料分类树失败，请稍后再试');
    categoryTree.value = [];
  }
};

const handleCategorySelect = (data) => {
  console.log('选中分类:', data);
  selectedCategoryId.value = data.orderId;
  // 根据选中的分类加载物料
  searchMaterials();
};

const handleMaterialRowClick = (row) => {
  // 更新单选框选中值
  selectedMaterialId.value = row.id || row.orderId;
  // 保存选中的物料
  selectedMaterial.value = row;
  console.log('选中物料:', row);
};

const handleRadioChange = (row) => {
  selectedMaterial.value = row;
  console.log('单选框选中物料:', row);
};

const selectMaterial = (row) => {
  console.log('选择物料:', row);
  // 设置物料信息到表单
  formData.materialId = row.id || row.orderId || '';
  formData.materialCode = row.materialCode || '';
  formData.materialName = row.materialName || '';
  formData.specification = row.specification || '';
  
  // 关闭对话框
  materialSelectorVisible.value = false;
  
  // 提示用户
  ElMessage.success(`已选择物料: ${row.materialName}`);
};

const confirmSelection = () => {
  if (selectedMaterial.value) {
    selectMaterial(selectedMaterial.value);
  } else {
    ElMessage.warning('请先选择一个物料');
  }
};

// 初始化物料选择器
const initMaterialSelector = () => {
  // 重置选中的物料
  selectedMaterial.value = null;
  selectedMaterialId.value = '';
  selectedCategoryId.value = null;
  
  // 加载分类树
  loadCategoryTree();
  // 加载物料列表
  searchMaterials();
};

// 打开物料选择器
const openMaterialSelector = () => {
  materialSelectorVisible.value = true;
  // 初始化选择器
  initMaterialSelector();
};

// 导出
const onExport = () => {
  ElMessage.info('导出功能待实现');
  // 实际项目中可以调用后台导出API
};

// 减少数量
const decreaseQuantity = () => {
  if (formData.quantity > 1) {
    formData.quantity--;
  }
};

// 增加数量
const increaseQuantity = () => {
  formData.quantity++;
};

// 删除单个SN码
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除 ${row.materialName || 'SN码'} 的记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    loading.value = true;
    
    // 调用后台删除接口
    const response = await http.post(`/api/SNTables/RemSNTable?id=${row.id}`);
    
    if (response && response.status) {
      ElMessage.success('删除成功');
      getTableData(); // 重新加载数据
    } else {
      ElMessage.error(response?.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除SN码
const onDeleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    loading.value = true;
    
    // 获取所有选中记录的ID
    const ids = selectedRows.value.map(row => row.id).join(',');
    
    // 调用后台批量删除接口
    const response = await http.post(`/api/SNTables/RemSNTable?id=${ids}`);
    
    if (response && response.status) {
      ElMessage.success('批量删除成功');
      getTableData(); // 重新加载数据
    } else {
      ElMessage.error(response?.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    await formRef.value.validate();
    
    submitLoading.value = true;
    
    // 准备提交的数据
    const submitData = {
      materialId: formData.materialId,
      batchNumber: formData.batchNumber || '',
      quantity: formData.quantity,
      prefix: formData.prefix || ''
    };
    
    // 调用后台API创建SN码
    const response = await http.post(`${baseApiUrl}/GenerateSN`, submitData);
    
    if (response && response.status) {
      ElMessage.success('SN码生成成功');
      addDialogVisible.value = false;
      getTableData(); // 重新加载数据
    } else {
      ElMessage.error(response?.message || '生成SN码失败');
    }
  } catch (error) {
    console.error('生成SN码失败:', error);
    ElMessage.error('生成SN码失败，请稍后重试');
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  height: calc(100vh - 40px); /* 减去上下padding */
  display: flex;
  flex-direction: column;
}

.filter-card {
  background: #f5f7fa;
  padding: 16px 16px 0 16px;
  border-radius: 6px;
  margin-bottom: 10px;
  flex-shrink: 0;
}

.filter-form {
  margin-bottom: 0;
}

.operation-area {
  margin: 10px 0;
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

/* 表格容器占满剩余空间 */
.table-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

/* 表格样式 */
:deep(.el-table) {
  height: 100% !important;
}

/* 分页容器固定在底部 */
.pagination-container {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
  padding: 5px 0;
}

/* 弹窗样式 */
:deep(.custom-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.custom-dialog .el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.custom-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.custom-dialog .el-dialog__footer) {
  padding: 10px 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-form .el-form-item {
  margin-bottom: 18px;
}

.input-with-icon {
  display: flex;
  align-items: center;
}

.search-btn {
  margin-left: 5px;
}

.quantity-input {
  display: flex;
  align-items: center;
}

.quantity-input .el-input-number {
  margin: 0 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item.is-required .el-form-item__label:before) {
  color: #f56c6c;
}

.dialog-footer {
  text-align: right;
}

/* 物料选择对话框样式 */
.material-selector-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__header) {
    padding: 15px 20px;
    background-color: #f5f7fa;
    margin-right: 0;
  }
  
  :deep(.el-dialog__title) {
    font-weight: bold;
    font-size: 16px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 10px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.material-selector-container {
  display: flex;
  flex-direction: column;
  height: 550px;
}

.selector-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.category-tree {
  width: 250px;
  border-right: 1px solid #e4e7ed;
  overflow: auto;
  padding: 10px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.tree-title {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

.material-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow: hidden;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.custom-tree-node .el-icon {
  margin-right: 5px;
  color: #909399;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row.current-row) {
  background-color: #ecf5ff;
}

/* 表格中的radio样式 */
:deep(.el-radio) {
  margin-right: 0;
  display: flex;
  justify-content: center;
}

:deep(.el-radio__label) {
  display: none;
}

/* 输入框样式 */
.input-with-icon {
  display: flex;
  align-items: center;
}

.search-btn {
  margin-left: 5px;
}

:deep(.el-input__inner[readonly]) {
  cursor: pointer;
  background-color: #f5f7fa;
}
</style>
